<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>game1</title>
    <style media="screen">
        canvas {
            border: 1px black solid;
        }

    </style>
</head>

<body>
    <canvas id="id-canvas" width="500" height="600"></canvas>
    <script type="text/javascript" >
        var log = console.log.bind(console)

        var imageFromPath = function (path) {
            var img = new Image
            img.src = path
            return img
        }
        var Paddle = function() {
            var image = imageFromPath('paddle.png')
            var o = {
                image:image,
                x:100,
                y:200,
                speed:5
            }
            o.moveLeft = function () {
                o.x -=o.speed
            }

            o.moveRight = function () {
                o.x += o.speed
            }

            return o
        }


        var GuaGame = function () {
            var g = {}
            var canvas = document.querySelector('#id-canvas')
            var context = canvas.getContext('2d')

            g.canvas = canvas
            g.context = context

            setInterval(function(){

                //update
                g.update()

                context.clearRect(0, 0, canvas.width, canvas.height)
                //draw
                g.draw()

            }, 1000/30)
            
            return g
        }
        var _main = function(){
            log('_main')
            

            var paddle = Paddle()

            var leftDown = false
            var rightDown = false

            var game = new GuaGame

            //events
            window.addEventListener('keydown',function(event){
                //log(event)
                log('keydown')
                var key = event.key
                if(key == 'a')
                {
                    leftDown = true
                }
                else if( key == 'd')
                {
                    rightDown = true
                }
            })

            window.addEventListener('keyup',function(event){
                //log(event)
                log('keyup')
                var key = event.key
                if(key == 'a')
                {
                    leftDown = false
                }
                else if( key == 'd')
                {
                    rightDown = false
                }
            })

            game.update = function () {
                //update
                if(leftDown)
                {
                    paddle.moveLeft()
                }
                else if (rightDown) {
                    paddle.moveRight()
                }
                
            }

            game.draw = function (){
                //draw
                game.context.drawImage(paddle.image, paddle.x, paddle.y)

            }
            }
        _main()
    </script>
</body>


</html>


    
